package com.example.zcapi.http.model

import android.net.Uri
import android.webkit.MimeTypeMap
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.SPUtils
import com.example.zcapi.Configs.LOCAL_IP_PORT
import com.example.zcapi.http.DownloadFile
import com.google.gson.reflect.TypeToken
import com.jeremyliao.liveeventbus.LiveEventBus



/**
 * author : Android 轮子哥
 * github : https://github.com/getActivity/EasyHttp
 * time   : 2022/03/22
 * desc   : Http 缓存管理器
 */
object HttpCacheManager {

    private var TAG = "HttpCacheManager"

    const val APP_CACHE_CONFIG = "app_cache_config"

    const val APP_CACHE_TIME_STAMP = "app_cache_time_stamp"
    //   private static final String HTTP_CACHE_CONTENT = "http_cache_content";
    //   private static final String HTTP_CACHE_TIME = "http_cache_time";
    /**
     * 读取缓存
     */
    fun getHttpCache(url: String): DownloadFile {
        var result = SPUtils.getInstance(APP_CACHE_CONFIG).getString(url)
       try {
           if(result.isNullOrEmpty()){
               val uri = Uri.parse(url)
               val fileName = uri.lastPathSegment
               var downloadFile = DownloadFile()
               downloadFile.url = url

               val extension = MimeTypeMap.getFileExtensionFromUrl(uri.toString())
               var fileNameNoExtent = uri.lastPathSegment?.replace(".$extension","")

               if(extension.equals("m3u8",true)){
                   downloadFile.path = "$LOCAL_IP_PORT$fileNameNoExtent/$fileNameNoExtent.m3u8"
               }else{
                   downloadFile.path = LOCAL_IP_PORT + fileName
               }

               downloadFile.status = 0
               downloadFile.timeStamp = System.currentTimeMillis()
               setHttpCache(url,downloadFile)
               return downloadFile
           }else {
               return GsonUtils.fromJson(result, object : TypeToken<DownloadFile>() {}.type)
           }
       }catch (e:Exception){
           val uri = Uri.parse(url)
           val fileName = uri.lastPathSegment
           var downloadFile = DownloadFile()
           downloadFile.url = url

           val extension = MimeTypeMap.getFileExtensionFromUrl(uri.toString())
           var fileNameNoExtent = uri.lastPathSegment?.replace(".$extension","")

           if(extension.equals("m3u8",true)){
               downloadFile.path = "$LOCAL_IP_PORT$fileNameNoExtent/$fileNameNoExtent.m3u8"
           }else{
               downloadFile.path = LOCAL_IP_PORT + fileName
           }
           downloadFile.status = 0
           downloadFile.timeStamp = System.currentTimeMillis()
           setHttpCache(url,downloadFile)
           return downloadFile
       }
    }



    /**
     * 写入缓存
     */
    @JvmStatic
    fun setHttpCache(url: String,fileInfo: DownloadFile) {
        fileInfo.timeStamp = System.currentTimeMillis()
        SPUtils.getInstance(APP_CACHE_CONFIG).put(url, GsonUtils.toJson(fileInfo), true)
        SPUtils.getInstance(APP_CACHE_TIME_STAMP).put(url,fileInfo.timeStamp)
    }

    @JvmStatic
    fun clear(){
        SPUtils.getInstance(APP_CACHE_CONFIG).clear()
    }



    /**
     * 生成缓存的 key
     */
    //   public static String generateCacheKey(@NonNull HttpRequest<?> httpRequest) {
    //      IRequestApi requestApi = httpRequest.getRequestApi();
    //      return "请替换成当前的用户 id" + "\n" + requestApi.getApi() + "\n" + GsonFactory.getSingletonGson().toJson(requestApi);
    //   }
    /**
     * 清理缓存
     */
    @JvmStatic
    fun clearHttpCache() {
        SPUtils.getInstance(APP_CACHE_CONFIG).clear()
    }

    /**
     * 获取 Http 写入缓存的时间
     */
    fun getHttpCacheTime(cacheKey: String?): Long {
        return SPUtils.getInstance(APP_CACHE_CONFIG).getLong(cacheKey!!, 0)
    }

    /**
     * 设置 Http 写入缓存的时间
     */
    @JvmStatic
    fun setHttpCacheTime(cacheKey: String?, cacheTime: Long) {
        SPUtils.getInstance(APP_CACHE_CONFIG).put(cacheKey!!, cacheTime, true)
    }

    /**
     * 判断缓存是否过期
     */
    @JvmStatic
    fun isCacheInvalidate(cacheKey: String?, maxCacheTime: Long): Boolean {
        if (maxCacheTime == Long.MAX_VALUE) {
            // 表示缓存长期有效，永远不会过期
            return false
        }
        val httpCacheTime = getHttpCacheTime(cacheKey)
        return if (httpCacheTime == 0L) {
            // 表示不知道缓存的时间，这里默认当做已经过期了
            true
        } else httpCacheTime + maxCacheTime < System.currentTimeMillis()
    }
}